package com.zyit.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyit.dto.HospitalDto;
import com.zyit.pojo.Hospital;
import com.zyit.service.HospitalService;
import com.zyit.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Tag(name = "医院管理")
@RestController
@RequestMapping("/admin/hos")
public class HospitalController {
    @Autowired
    private HospitalService hospitalService;

    @Operation(summary = "分页条件查询")
    @PostMapping("/page")
    public Result findPage(@RequestBody HospitalDto hospitalDto){
        return hospitalService.findPage(hospitalDto);
    }

    @Operation(summary = "修改医院信息")
    @PutMapping
    public int edit(@RequestBody Hospital hospital) {
        return hospitalService.edit(hospital);
    }

    @Operation(summary = "上传医院信息")
    @PostMapping
    public int add(@RequestBody Hospital hospital) {
        return hospitalService.add(hospital);
    }

    @Operation(summary = "上传医院信息前重复校验")
    @GetMapping("/{hoscode}")
    public Result checkForAdd(@PathVariable String hoscode) {
        Hospital hospital = hospitalService.findByCode(hoscode);
        if(hospital!=null){
            return new Result("601","该医院已存在，请勿重复上传");
        }
        return Result.ok();
    }

    @Operation(summary = "上传医院Logo",description = "上传到项目根目录")
    @PostMapping("/logo")
    public String uploadLogo(MultipartFile file, HttpServletRequest req) {
        //获取根目录
        String realPath = req.getServletContext().getRealPath("/");
        //文件夹
        File folder = new File(realPath+"/img/");
        //判断文件是否存在
        if (!folder.exists()){//不存在，则创建
            //这里需要使用mkdirs，因为为多层目录
            folder.mkdirs();
        }
        //获取文件后缀+文件名
        String oldName = file.getOriginalFilename();
        //将后缀加到新的文件名上
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            //文件保存
            file.transferTo(new File(folder,newName));
            //获取请求协议                            获取主机名                       获取端口
            String s = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img/" + newName;//文件的访问路径
            System.out.println(s);
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;
    @Operation(summary = "上传医院Logo到oss",description = "上传到阿里云oss")
    @PostMapping("/oss")
    public String uploadLogoToOss(MultipartFile file) {
        try {
            //创建oss实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            //获取上传文件的输入流
            InputStream fileInputStream = file.getInputStream();
            //获取原文件名
            String filename = file.getOriginalFilename();
            if (StringUtils.isBlank(filename)) {
                return "";
            }
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
            filename = currentTime + filename;
            //上传到指定目录的指定文件
            filename = "oss/upload/" + filename;
            /*
             * 调用OSS实现文件的上传
             * 第一个参数:Bucket名称
             * 第二个参数:上传到oss的指定路径和文件名称, oss/image/xx.png
             * 第三个参数:上传文件输入流
             */
            ossClient.putObject(bucketName, filename, fileInputStream);
            //关闭OSSClient
            ossClient.shutdown();
            //返回上传到OSS的文件的URL
            String url = "http://"+bucketName+"."+endpoint+"/"+filename;
            System.out.println(url);
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


}
